package com.sky.service.impl;

import com.aliyuncs.ecs.transform.v20140526.DescribeImageSharePermissionResponseUnmarshaller;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 添加到购物车
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveShopCart(ShoppingCartDTO dto) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //判断购物信息是否已经存在
        List<ShoppingCart> list =shoppingCartMapper.list(shoppingCart);
        if(list!=null && list.size()==1){
            ShoppingCart shoppingCart1 = list.get(0);
            Integer number = shoppingCart1.getNumber();
            shoppingCart.setNumber(number+1);
            shoppingCartMapper.updateNumberById(shoppingCart1);
        }else{
            if(shoppingCart.getDishId()!=null){
                Dish dish =dishMapper.getById(shoppingCart.getDishId());
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
            }else{
                Setmeal setmeal =setmealMapper.getById(shoppingCart.getSetmealId().intValue());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());

            }
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartMapper.save(shoppingCart);

        }

    }

    @Override
    public List<ShoppingCart> list() {
     ShoppingCart shoppingCart = new ShoppingCart();
     shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        return list;
    }

    @Override
    public void removeAll() {
        shoppingCartMapper.removeAll(BaseContext.getCurrentId());
    }
}
